<template>
  <div class="customer-plan-table-container">
    <el-table
      stripe
      :data="disposeFormListViewTime(planList, columns)"
      :highlight-current-row="false"
      header-row-class-name="common-list-table-header__v2"
      row-class-name="customer-plan-table-row"
      @sort-change="sortChange"
      v-loading="loading"
      v-bind="extraAttrs">
      <el-table-column
        v-for="(column, index) in columns"
        v-if="column.show"
        :key="`${column.field}_${index}`"
        :label="column.label"
        :prop="column.field"
        :width="column.width"
        :min-width="column.minWidth"
        :sortable="column.sortable"
        :show-overflow-tooltip="column.tooltip"
        :align="column.align">
        <template slot-scope="scope">
          <template v-if="column.field === 'name'">
            <a href=":javascript" @click="openDetail" :data-id="scope.row.id" class="plan-link">{{scope.row[column.field]}}</a>
          </template>
          <template v-else-if="column.field === 'templateId'">
            {{scope.row.task.templateName}}
          </template>
          <template v-else-if="column.field === 'createUserId'">
            <template v-if="isOpenData && scope.row.createUserStaffId">
              <open-data type='userName' :openid="scope.row.createUserStaffId"></open-data>
            </template>
            <template v-else>
              {{scope.row.createUserName}}
            </template>
          </template>
          <template v-else-if="column.field === 'endSetting'">
            <template v-if="scope.row.endSetting.endBy === 'date'">
              {{scope.row.endSetting.value | fmt_datetime}}
            </template>
            <template v-else>
              {{ $t('product.detail.planTable.text1' , {count : scope.row.endSetting.value}) }}
            </template>
          </template>
          <template v-else-if="column.field === 'createdTasks' && scope.row[column.field]">
            <template v-if="scope.row[column.field].length">
              <el-popover
                placement="left"
                width="360"
                trigger="hover">
                <div slot="reference">{{scope.row[column.field].length}}</div>
                <ul class="plan-created-task-list">
                  <li v-for="task in scope.row[column.field]" :key="task.taskId">
                    {{ $t('product.detail.type.task.taskNo') }}：{{task.taskNo}} {{ $t('common.base.createTime') }}：{{task.createTime | fmt_datetime}}
                  </li>
                </ul>
              </el-popover>
            </template>
            <template v-else>
              {{scope.row[column.field].length}}
            </template>
          </template>
          <template v-else-if="column.field === 'periodSetting'">
            每{{scope.row[column.field].period + scope.row[column.field].periodUnit}}
          </template>
          <template v-else-if="column.field === 'action'">
            <el-button 
              v-if="hasEditCustomerAuth"
              class="delete-plan-btn" 
              type="text" 
              @click="deletePlan(scope.row)" 
              :disabled="pending[scope.row.id]"
              size="small">{{$t('common.base.delete')}}</el-button>
          </template>
          <template v-else>
            {{ $formatFormField(column, scope.row) }}
          </template>
        </template>
      </el-table-column>

      <div slot="empty" class="empty-table-text">
        <p>{{$t('product.detail.planTable.tip1')}}</p>
        <p>{{$t('product.detail.planTable.tip2')}}</p>
      </div>
    </el-table>

    <!-- 分页 -->
    <BaseAddOnPagination :paginationInfo="searchModel" @pageJump="jump" @sizeChange="handleSizeChange" />
  </div>
</template>

<script>
import { formatDate, useFormTimezone } from "pub-bbx-utils";
import platform from "@src/platform";
import { getPlanOfProduct } from "@src/api/ProductApi";
import { deletePlanTask } from "@src/api/TaskApi.ts";
import { isOpenData } from '@src/util/platform'
import { safeNewDate } from '@src/util/time';
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { getRootWindow } from '@src/util/dom';

export default {
  name: "plan-table",
  props: {
    shareData: {
      type: Object,
      default: () => ({})
    },
    extraAttrs: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      ...useFormTimezone(),
      isOpenData,
      planList: [],
      pending: {},
      columns: this.buildColumns(),
      loading: false,
      searchModel: {
        pageSize: 10,
        pageNum: 1,
        totalItems: 0,
        orderDetail: {}
      }
    }
  },
  computed: {
    product(){
      return this.shareData.product || {};
    },
    productId() {
      return this.shareData.product.id;
    },
    /** 是否允许操作 */
    allowOperate(){
      return !this.product.isDelete;
    },
    /** 是否有编辑客户的权限 */
    hasEditCustomerAuth(){
      return this.shareData.allowEditCustomer
    },
    // 华大基因灰度
    isBgiSaas() {
      const RootWindow = getRootWindow(window)
      return Boolean(RootWindow.grayAuth?.bgiSaas)
    }
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    sortChange({ prop, order, }) {
      this.searchModel.orderDetail = {
        column: prop,
        sequence: order === "ascending" ? "ASC" : "DESC",
        isSystem: 1,
      };
      this.fetchData();
    },
    async deletePlan(plan) {
      try {
        const res = await platform.confirm(this.$t('product.detail.planTable.tip3'));
        if (!res) return;
        this.pending[plan.id] = true;

        const reqRes = await deletePlanTask({ids: [plan.id], });
        delete this.pending[plan.id];

        if (!reqRes.status) {
          this.fetchData();
          // 更新下产品详情页面计划任务数量
          this.$eventBus.$emit('product_view_plan_update');
        } else {
          platform.alert(reqRes.message);
        }
        this.$eventBus.$emit("customer_info_record.update_record_list");
      } catch (e) {
        console.error("deletePlan catch an err", e);
      }
    },
    jump(pN) {
      this.searchModel.pageNum = pN;
      this.fetchData();
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNum = 1;
      this.fetchData();
    },
    fetchData() {
      const {pageNum, pageSize, orderDetail, } = this.searchModel;
      const params = {
        productId: this.productId,
        pageNum,
        pageSize,
      };

      if (Object.keys(orderDetail).length) {
        params.orderDetail = orderDetail;
      }

      this.loading = true;
      getPlanOfProduct(params)
        .then(res => {
          if (!res) return;
          const planList = res?.result?.list || []
          this.planList = planList
            .map(plan => {
              plan.createTime = formatDate(safeNewDate(plan.createTime), "YYYY-MM-DD HH:mm:ss");
              plan.nextTaskCreateTime = plan.nextTaskCreateTime ? formatDate(safeNewDate(plan.nextTaskCreateTime), "YYYY-MM-DD HH:mm:ss") : "";
              plan.createdTasks = Array.isArray(plan.createdTasks) ? plan.createdTasks : []
              this.$set(this.pending, plan.id, false);
              return Object.freeze(plan);
            });
          this.searchModel.totalItems = res.result?.total || 0;
          this.loading = false;
        })
        .catch(e => {
          this.loading = false;
          console.error("fetchData caught e", e)
        });
    },
    buildColumns() {
      return [{
        label: this.$t('common.base.name'),
        field: "name",
        show: true,
        tooltip: true,
        sortable: "custom",
      }, {
        label: this.$t('product.detail.type.task.templateId'),
        field: "templateId",
        show: true,
        tooltip: true,
        sortable: "custom",
        minWidth:'100px'
      }, {
        label: this.$t('common.base.createUser'),
        field: "createUserId",
        show: true,
        tooltip: true,
        sortable: "custom",
        minWidth:'100px'
      }, {
        label: this.$t('common.base.createTime'),
        field: "createTime",
        show: true,
        tooltip: true,
        sortable: "custom",
        minWidth:'100px'
      }, {
        label: this.$t('product.detail.type.plan.endSetting'),
        field: "endSetting",
        show: true,
        tooltip: true,
        sortable: "custom",
        minWidth:'100px'
      }, {
        label: this.$t('product.detail.type.plan.periodSetting'),
        field: "periodSetting",
        show: true,
        tooltip: true,
        width: "100px",
        sortable: "custom",
        minWidth:'100px'
      }, {
        label: this.$t('product.detail.type.plan.nextTaskCreateTime'),
        field: "nextTaskCreateTime",
        show: true,
        tooltip: true,
        width: "130px",
        sortable: "custom",
        minWidth:'130px'
      }, {
        label: this.$t('product.detail.type.plan.totalTaskNumber'), // 总工单数
        field: 'totalTaskNumber',
        show: true,
        tooltip: true,
        width: '130px',
      },{
        label: this.$t('product.detail.type.plan.uncreateTaskNumber'), // 待创建工单数
        field: 'uncreatedTaskNumber',
        show: true,
        tooltip: true,
        width: '130px',
      },{
        label: this.$t('product.detail.type.plan.createTaskNumber'), // 已创建工单数
        field: 'createdTasks',
        show: true,
        tooltip: false,
        width: '95px',
        sortable: 'custom',
      },{
        label: this.$t('product.detail.type.plan.finishedTaskNumber'), // 已完成工单数
        field: 'finishedTaskNumber',
        show: true,
        tooltip: true,
        width: '130px',
      }, {
        label: this.$t('common.base.operation'),
        field: "action",
        show: true,
        tooltip: false,
        width: "81px"
      }]
    },
    /* 新tab 打开计划任务 */
    openDetail(event) {
      event.preventDefault();
      if (!window.frameElement) return;
      const fromId = window.frameElement.getAttribute("id");
      const $el = event.target;
    
      if(this.isBgiSaas) {
        openAccurateTab({
          type: PageRoutesTypeEnum.PagePlanTaskView,
          key: $el.dataset.id,
          params: `id=${$el.dataset.id}`,
          fromId
        })
      } else {
        openAccurateTab({
          type: PageRoutesTypeEnum.PagePlanTaskEdit,
          params: `id=${$el.dataset.id}`,
          key: $el.dataset.id,
          fromId
        })
      }
    }
  },
}
</script>

<style lang="scss">

  .plan-created-task-list {
    padding: 0;
    margin: 0;
    font-size: 12px;
    li {
      padding: 0;
      margin: 0;
      list-style: none;
    }
  }

  .customer-plan-table-container {
    padding: 16px;

    .plan-link {
      @include fontColor();
    }

    .delete-plan-btn {
      color: $color-danger;
    }

    .delete-plan-btn.is-disabled,
    .delete-plan-btn.is-disabled:hover,
    .el-button.delete-plan-btn:focus {
      color: #c0c4cc;
      cursor: not-allowed;
      background-image: none;
    }

    .empty-table-text {
      width: 400px;
      text-align: left;
      p {
        margin: 0;
        line-height: 20px;
      }
    }
  }
</style>